package perf.store;

import java.io.File;

import com.db4o.Db4o;
import com.db4o.ObjectContainer;
import com.db4o.config.Configuration;
import com.db4o.ta.TransparentActivationSupport;

public class ObjectStore {

	ObjectContainer store;
	ObjectList lister;
	ObjectModify modifyer;
	
	public ObjectStore( File db ) {
		store = ObjectStore.startDb( db );
		lister = new ObjectList( store );
		modifyer = new ObjectModify( store, lister );
	}
	
	public static void create( File dbfile ) throws RuntimeException {
		if ( dbfile.exists() ) {
			throw new RuntimeException( "Cannot create database " +
					"because file already exists: " + dbfile );
		}
		ObjectContainer container = ObjectStore.startDb( dbfile );
		container.close();
	}
	
	public ObjectList list( ) {
		return lister;
	}
	
	public ObjectModify modify( ) {
		return modifyer;
	}
	
	public void close( ) {
		if ( store != null ) {
			store.close();
		}
	}
	
	private static ObjectContainer startDb( File f ) {
		Configuration c = Db4o.newConfiguration();
		c.add( new TransparentActivationSupport() );
		return Db4o.openFile( c, f.getPath() );
	}

}
